package com.lin.wx.official.account.service.impl;


import com.lin.wx.official.account.manager.MessageHandler;
import com.lin.wx.official.account.manager.WxMessageHelper;
import com.lin.wx.official.account.model.vo.WxMessageVO;
import com.lin.wx.official.account.service.IWxMessageBiz;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author linjiang
 * @date 2024/6/20
 * @fn
 */
@Slf4j
@Service
public class WxMessageBiz implements IWxMessageBiz {

    @Resource
    WxMessageHelper wxMessageHelper;

    @Override
    public String handleXmlMessage(String appId, WxMpXmlMessage message) {
        String msgType = message.getMsgType();
        if (StringUtils.isNotBlank(message.getEvent())) {
            msgType = msgType.concat(":").concat(message.getEvent());
        }

        MessageHandler handler = wxMessageHelper.get(msgType);
        WxMessageVO wxMessageVO = buildWxXmlMessageVO(appId, message);
        return handler.handleRecieveMessage(wxMessageVO);
    }


    /**
     * 将转换后的消息体封装成开发者自定义VO
     *
     * @param appId
     * @param message
     * @return
     */
    private WxMessageVO buildWxXmlMessageVO(String appId, WxMpXmlMessage message) {
        return WxMessageVO.builder()
                .appId(appId)
                .toUser(message.getToUser())
                .fromUser(message.getFromUser())
                .msgType(message.getMsgType())
                .event(message.getEvent())
                .createTime(message.getCreateTime())
                .eventKey(message.getEventKey())
                .ticket(message.getTicket())
                .content(message.getContent())
                .msgId(message.getMsgId())
                .build();
    }

}
